package com.hermeneute.fsa.popup.actions;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionDelegate;

public class AddNature extends ActionDelegate implements IObjectActionDelegate {

	IProject project = null;
	public AddNature() {
	}

	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
	}

	public void run(IAction action) {
		try {
			int i;
			String[] newNatures = null;
			boolean isFSAProject = false;
			IProjectDescription description = project.getDescription();
			String[] natures = description.getNatureIds();
			for (i = 0; i < natures.length; i++) {
				if ("com.hermeneute.fsa.nature".equals(natures[i])) {
					isFSAProject = true;
				}
			}
			if (isFSAProject) {
				newNatures = new String[natures.length - 1];
				for (i = 0; i < natures.length; i++) {
					if (!"com.hermeneute.fsa.nature".equals(natures[i])) {
						newNatures[i] = natures[i];
					}
				}
				MessageDialog.openInformation(
			         	PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
			         "Hermeneute",
			         "FSA nature removed from "+project);

			} else {
				newNatures = new String[natures.length + 1];
				System.arraycopy(natures, 0, newNatures, 0, natures.length);
				newNatures[natures.length] = "com.hermeneute.fsa.nature";
				MessageDialog.openInformation(
			         	PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(),
			         "Hermeneute",
			         project+" has now FSA nature");
			}
			description.setNatureIds(newNatures);
			project.setDescription(description, null);
		} catch (CoreException e) {
			// Something went wrong
			e.printStackTrace();
		}
	}

	   public void selectionChanged(IAction action,
               ISelection selection)
	   {
		   project = null;
		   if(selection instanceof IStructuredSelection)
		   {
			   IStructuredSelection structuredSelection =
				   (IStructuredSelection)selection;
			   if(structuredSelection.size() == 1)
			   {
				   Object selectedResource =
					   structuredSelection.getFirstElement();
				   if(selectedResource instanceof IProject)
					   project = (IProject)selectedResource;
			   }
		   }
	   }
}
